package com.miao.im.biz;

import com.miao.im.common.Constant;
import com.miao.im.common.Message;
import com.miao.im.common.annotation.MessageCommand;
import com.miao.im.common.enums.Command;
import com.miao.im.dto.SocketMessageDto;
import com.miao.im.model.P2PRequestModel;
import com.miao.im.server.session.SessionContext;
import com.miao.im.server.session.SessionManager;
import com.miao.im.support.handler.AbstractMessageHandler;
import com.miao.im.support.mq.IProducerMessageService;
import com.miao.im.support.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

/**
 * @Auther: miaoguoxin
 * @Date: 2021/3/17 17:27
 * @Description:
 */
@Component
@MessageCommand(Command.P2P_NOTIFY_ACK)
public class P2PNotifyAckRequestHandler extends AbstractMessageHandler<P2PRequestModel.P2PRequest> {

    @Autowired
    private IProducerMessageService messageService;


    @Override
    protected void doRead(P2PRequestModel.P2PRequest body, Message message) {
        Message request = Message.writeRequest(message.getVersion(), message.getSequence(), Command.P2P_NOTIFY_TO_SENDER_ACK.getCode(), body.toByteArray());
        SessionManager.sendToUser(String.valueOf(body.getFromUserId()), request);
    }

    @Override
    protected Mono<Void> doDispatch(P2PRequestModel.P2PRequest body, Message message, SessionContext sessionContext) {
        String fromRoutingKey = body.getFromRoutingKey();
        //本机不通过mq转发
        if (Constant.DISPATCHER_ROUTING_KEY_NAME.equals(fromRoutingKey)) {
            this.doRead(body, message);
        } else {
            SocketMessageDto messageDto = new SocketMessageDto(message);
            messageService.send(Constant.DISPATCHER_EXCHANGE, fromRoutingKey, JsonUtil.toJSONStr(messageDto));
        }
        return Mono.empty();
    }

}
